package gorms

import (
	"strings"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

type GDB struct {
	*gorm.DB
}

func newDB(db *gorm.DB) *GDB {
	return &GDB{DB: db}
}

func (this *GDB) ID(arg interface{}) *GDB {
	return newDB(this.DB.Where("ID=?", arg))
}

func (this *GDB) Where(query interface{}, args ...interface{}) *GDB {
	return newDB(this.DB.Where(query, args...))
}

func (this *GDB) Like(query, arg string) *GDB {
	return newDB(this.DB.Where(query+" like ?", "%"+arg+"%"))
}

func (this *GDB) In(query string, args ...interface{}) *GDB {
	return newDB(this.DB.Where(query+" IN (?)", args...))
}

func (this *GDB) Limit(size int, start ...int) *GDB {
	db := this.DB
	if size > 0 {
		db = db.Limit(size)
		if len(start) > 0 {
			db = db.Offset(start[0])
		}
	}
	return newDB(db)
}

func (this *GDB) Desc(name string) *GDB {
	return newDB(this.DB.Order(name + " desc"))
}

func (this *GDB) Asc(name string) *GDB {
	return newDB(this.DB.Order(name + " asc"))
}

func (this *GDB) Create(v interface{}) *GDB {
	return newDB(this.DB.Create(v))
}

func (this *GDB) Session(fn func(db *gorm.DB) error) error {
	return NewSession(this.DB, fn)
}

func (this *GDB) Session2(fn func(db *GDB) error) error {
	return NewSession2(this.DB, fn)
}

// Update 更新
// @data,更新的结构
// @cols,更新的字段
func (this *GDB) Update(data interface{}, cols ...string) *GDB {
	session := this.DB.Model(data)
	if len(cols) > 0 {
		list := []string{}
		for _, v := range cols {
			list = append(list, strings.Split(v, ",")...)
		}
		session = session.Select(list)
	}
	return newDB(session.Updates(data))
}

//=====================================================

//建表
func (this *GDB) CreateTable(tables ...interface{}) error {
	var er error
	for _, table := range tables {
		if !this.DB.HasTable(table) {
			if err := this.DB.CreateTable(table).Error; err != nil {
				er = err
			}
		}
	}
	return er
}

////试用
////是否存在,错误则退出
//func (this *GDB) Exist(v interface{}) bool {
//	err := this.DB.Take(v).Error
//	if err != nil && err.Error() != ErrNotFind {
//		in.Err(err)
//	}
//	return err == nil
//}

////剥离是否存在和错误
////模仿xorm
//func (this *GDB) Get(v interface{}) (bool, error) {
//	err := this.DB.Take(v).Error
//	if err != nil && err.Error() != ErrNotFind {
//		return false, err
//	}
//	return err == nil, nil
//}
